package com.wing.product.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.bill.model.entity.BillDetailInfo;
import com.wing.bill.model.entity.WarehouseBill;
import com.wing.bill.model.enums.OrderSourceEnum;
import com.wing.bill.service.WarehouseBillDetailService;
import com.wing.bill.service.WarehouseBillService;
import com.wing.common.constant.SecurityConstants;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.platform.order.model.entity.Product;
import com.wing.product.model.entity.*;
import com.wing.product.model.request.WarehouseTransferOrderDetailForm;
import com.wing.product.model.request.WarehouseTransferOrderForm;
import com.wing.product.model.response.WarehouseOutboundOrderVO;
import com.wing.product.model.response.WarehouseTransferOrderDetailVO;
import com.wing.product.model.response.WarehouseTransferOrderVO;
import com.wing.web.utils.JwtUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.product.dao.WarehouseTransferOrderDao;
import org.springframework.transaction.annotation.Transactional;

@Service
public class WarehouseTransferOrderServiceImpl extends ServiceImpl<WarehouseTransferOrderDao, WarehouseTransferOrder> implements WarehouseTransferOrderService{


    @Autowired
    private WarehouseTransferOrderDetailService warehouseTransferOrderDetailService;

    @Autowired
    private WarehouseProductInventoryService warehouseProductInventoryService;

    @Autowired
    private WarehouseBillDetailService warehouseBillDetailService;

    @Autowired
    private WarehouseBillService warehouseBillService;

    @Autowired
    private WarehouseTransferOrderDao warehouseTransferOrderDao;


    @Override
    public Page<WarehouseTransferOrderVO> pageList4app(Page page, Map<String, Object> params) {
//        List<WarehouseTransferOrderVO> list = baseMapper.list4app(pg, paramMap);
        List<WarehouseTransferOrderVO> list = baseMapper.list4app(page, params);
        list.forEach(warehouseTransferOrderVO -> {
            if(JwtUtils.getClientId().equals(SecurityConstants.WAREHOUSE_CLIENT_ID)){
                warehouseTransferOrderVO.setLoginCustomerId(JwtUtils.getDepartmentId());
            }
        });
//        return new PageResult<>(list);

        page.setRecords(list);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean save(WarehouseTransferOrderForm warehouseTransferOrderForm) {
        WarehouseTransferOrder warehouseTransferOrder = new WarehouseTransferOrder();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(WarehouseTransferOrder.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(warehouseTransferOrderForm, warehouseTransferOrder,copyOptions);


        warehouseTransferOrder.setTransferCode(UniqueIdGeneratorUtil.generateUniqueId("GH", "yyyyMMddHHmmss", 1000, 9999));
        warehouseTransferOrder.setBuyerPhone(warehouseTransferOrderForm.getBuyerCustomerPhone());
        warehouseTransferOrder.setSellerPhone(warehouseTransferOrderForm.getSellerCustomerPhone());
        warehouseTransferOrder.setSellerContactId(warehouseTransferOrderForm.getSellerCustomerUser());
        warehouseTransferOrder.setBuyerContactId(warehouseTransferOrderForm.getBuyerCustomerUser());
        warehouseTransferOrder.setSellerConfirm(0);
        warehouseTransferOrder.setBuyerConfirm(0);
        warehouseTransferOrder.setTransferStatus(0);
        if(JwtUtils.getClientId().equals(SecurityConstants.ADMIN_CLIENT_ID)) {
            warehouseTransferOrder.setSource(OrderSourceEnum.PLATFORM.getCode());
        }
        if(JwtUtils.getClientId().equals(SecurityConstants.WAREHOUSE_CLIENT_ID)) {
            warehouseTransferOrder.setSource(OrderSourceEnum.CUSTOMER.getCode());
        }
        baseMapper.insert(warehouseTransferOrder);
        List<WarehouseTransferOrderDetail> orderDetailList = new ArrayList<>();
        for (WarehouseTransferOrderDetailForm warehouseTransferOrderDetailForm : warehouseTransferOrderForm.getWarehouseTransferOrderDetail()) {
            WarehouseTransferOrderDetail warehouseTransferOrderDetail = new WarehouseTransferOrderDetail();
            CopyOptions copyDetailOptions = CopyOptions.create()
                    .setEditable(WarehouseTransferOrderDetail.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(warehouseTransferOrderDetailForm, warehouseTransferOrderDetail,copyDetailOptions);
            warehouseTransferOrderDetail.setTransferCode(warehouseTransferOrder.getTransferCode());
            warehouseTransferOrderDetail.setTransferId(warehouseTransferOrder.getId());
            orderDetailList.add(warehouseTransferOrderDetail);
            //将锁定的物料根据系统捆包号锁定修改状态为6
            warehouseTransferOrderDao.updateUserBundleCode(6,warehouseTransferOrderDetailForm.getSysBundleCode());
//            warehouseProductInventoryService
        }
        warehouseTransferOrderDetailService.saveBatch(orderDetailList);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean adminTransferOrderConfirm(Long id) {
        List<WarehouseProductInventory> productInventoryList = new ArrayList<>();
        // 通过 过户订单id 查询过户订单详情
        List<WarehouseTransferOrderDetailVO> detailList = warehouseTransferOrderDetailService.getDetailBydTransferOrderId(id);
        //获取货主customerId
        WarehouseTransferOrder warehouseTransferOrder = baseMapper.selectById(id);
        // 通过订单id 库存货主
        detailList.forEach(warehouseTransferOrderDetail -> {
            WarehouseProductInventory warehouseProductInventory = warehouseProductInventoryService.getOne(new LambdaQueryWrapper<WarehouseProductInventory>().eq(WarehouseProductInventory::getSysBundleCode, warehouseTransferOrderDetail.getSysBundleCode()));
            //修改库存的原始客户id
            warehouseProductInventory.setOriginalCustomerId(warehouseProductInventory.getCustomerId());
            //修改库存的客户id
            warehouseProductInventory.setCustomerId(warehouseTransferOrder.getBuyerCustomerId());
            //修改库存的状态
            warehouseProductInventory.setProductStatus(3);
            productInventoryList.add(warehouseProductInventory);
        });
        warehouseProductInventoryService.updateBatchById(productInventoryList);
        //完成过户 需要修改账单
        if(warehouseBillDetailService.updateBillDetail(warehouseTransferOrder.getSellerCustomerId(),
                detailList.stream().map(WarehouseTransferOrderDetailVO::getSysBundleCode).collect(Collectors.toList()))){
            WarehouseBill warehouseBill;
            warehouseBill = warehouseBillService.isExistBill(warehouseTransferOrder.getBuyerCustomerId());
            // 先判断 头部账单是否存在
            if(ObjectUtil.isEmpty(warehouseBill)){
                //如果不存在 新增头部订单
                warehouseBill = warehouseBillService.createBill(warehouseTransferOrder.getSellerCustomerId());
            }
            //生成新的账单
           return warehouseBillDetailService.addBillDetail(warehouseTransferOrder.getBuyerCustomerId(), detailList.stream().map(
                   product -> {
                       BillDetailInfo detailInfo = new BillDetailInfo();
                       detailInfo.setSysBundleCode(product.getSysBundleCode());
                       detailInfo.setPrice(product.getPrice());
                       detailInfo.setTransferType(2);
                       return detailInfo;
                   }
           ).collect(Collectors.toList()),warehouseBill.getId());


//            List<BillDetailInfo> detailInfoList = new ArrayList<>();
//            for (WarehouseTransferOrderDetailVO product : detailList) {
//                BillDetailInfo detailInfo = new BillDetailInfo();
//                detailInfo.setSysBundleCode(product.getSysBundleCode());
//                detailInfo.setPrice(product.getPrice());
//                detailInfo.setTransferType(2);
//                detailInfoList.add(detailInfo);
//            }
//
//            warehouseBillDetailService.addBillDetail(
//                    warehouseTransferOrder.getBuyerCustomerId(),
//                    detailInfoList,
//                    warehouseBill.getId()
//            );
        }else {
            return false;
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateStatus(Long id, Integer status, String type) {
        WarehouseTransferOrder attr = new WarehouseTransferOrder();
        // 根据前端传入类型 判断 修改状态
        if("seller".equals(type)){
            attr.setId(id);
            attr.setSellerConfirm(status);
            attr.setSellerCustomerId(JwtUtils.getDepartmentId());
        }else if("buyer".equals(type)){
            attr.setId(id);
            attr.setBuyerConfirm(status);
            attr.setBuyerCustomerId(JwtUtils.getDepartmentId());
        }else {
            if(JwtUtils.getClientId().equals(SecurityConstants.ADMIN_CLIENT_ID)){
                attr.setId(id);
                attr.setTransferStatus(status);
                // 管理员确定，需要修改库存状态
                if(!adminTransferOrderConfirm(id)){
                    return JsonResult.fail("受理失败");
                }
            }
        }
        if(attr.getId() == null){
            return JsonResult.fail("不符合受理条件");
        }
        if (updateById(attr)) {
            return JsonResult.success("受理成功");
        }
        return JsonResult.fail("受理失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult retract(Long id, Integer status, String type,String sysBundleCode) {
        List<WarehouseTransferOrderDetail> warehouseTransferOrderDetailList=warehouseTransferOrderDetailService.getDetailByTransferOrderId(id);
        for(WarehouseTransferOrderDetail warehouseTransferOrderDetail:warehouseTransferOrderDetailList){
            //撤销的时候讲物料状态设置为3
            warehouseTransferOrderDao.updateUserBundleCode(3,warehouseTransferOrderDetail.getSysBundleCode());
        }
        WarehouseTransferOrder warehouseTransferOrder=warehouseTransferOrderDao.selectById(id);
        warehouseTransferOrder.setTransferStatus(2);
        warehouseTransferOrderDao.updateById(warehouseTransferOrder);
//        updateStatus(id,status,type);
        return JsonResult.success("受理成功");
    }
}
